import React, { useState, useEffect } from 'react'
import { View, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './index.scss'

// 定义账单数据类型
interface BillRecord {
  amount: string
  type: string | number
  selectedType: string
  remarks: string
  date: string
  selectedIcon: string
  id: string
}

// 定义统计数据类型
interface MonthStats {
  month: string
  income: number
  expense: number
}

const Discover = () => {
  const STORAGE_KEY = 'bill_records'
  const [list, setList] = useState<BillRecord[]>([])
  const [monthlyStats, setMonthlyStats] = useState<MonthStats[]>([])

  // 组件加载时读取数据
  useEffect(() => {
    loadBillRecords()
  }, [])

  // 从本地存储加载账单记录
  const loadBillRecords = async () => {
    try {
      const data = await Taro.getStorage({ key: STORAGE_KEY })
      if (data.data) {
        const records = JSON.parse(data.data)
        setList(records)
        calculateMonthlyStats(records)
      }
    } catch (error) {
      console.log('暂无账单记录')
      setList([])
    }
  }

  // 计算每月统计数据
  const calculateMonthlyStats = (records: BillRecord[]) => {
    const statsMap = new Map<string, { income: number; expense: number }>()

    records.forEach(record => {
      const date = new Date(record.date)
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
      
      if (!statsMap.has(monthKey)) {
        statsMap.set(monthKey, { income: 0, expense: 0 })
      }

      const stats = statsMap.get(monthKey)!
      const amount = parseFloat(record.amount)

      if (record.type === '0') {
        stats.income += amount
      } else {
        stats.expense += amount
      }
    })

    // 转换为数组并按月份排序
    const statsArray = Array.from(statsMap.entries())
      .map(([month, data]) => ({
        month,
        income: data.income,
        expense: data.expense
      }))
      .sort((a, b) => b.month.localeCompare(a.month)) // 倒序排列
      .slice(0, 6) // 只显示最近6个月

    setMonthlyStats(statsArray)
  }

  // 计算总收入和总支出
  const calculateTotal = () => {
    let totalIncome = 0
    let totalExpense = 0

    list.forEach(record => {
      const amount = parseFloat(record.amount)
      if (record.type === '0') {
        totalIncome += amount
      } else {
        totalExpense += amount
      }
    })

    return { totalIncome, totalExpense }
  }

  const { totalIncome, totalExpense } = calculateTotal()
  const balance = totalIncome - totalExpense

  return (
    <View className="discover-page">
      <View className="discover-header">
        <View className="header-title">数据统计</View>
      </View>

      {/* 总览卡片 */}
      <View className="overview-card">
        <View className="overview-item">
          <View className="overview-label">总收入</View>
          <View className="overview-value income">¥{totalIncome.toFixed(2)}</View>
        </View>
        <View className="overview-item">
          <View className="overview-label">总支出</View>
          <View className="overview-value expense">¥{totalExpense.toFixed(2)}</View>
        </View>
        <View className="overview-item">
          <View className="overview-label">结余</View>
          <View className={`overview-value ${balance >= 0 ? 'income' : 'expense'}`}>
            ¥{balance.toFixed(2)}
          </View>
        </View>
      </View>

      {/* 月度统计 */}
      <View className="stats-section">
        <View className="section-title">月度统计</View>
        
        <ScrollView scrollY className="month-list">
          {monthlyStats.length === 0 ? (
            <View className="empty-state">暂无数据</View>
          ) : (
            monthlyStats.map((stat, index) => {
              const monthBalance = stat.income - stat.expense
              return (
                <View key={index} className="month-item">
                  <View className="month-header">
                    <View className="month-name">{stat.month}</View>
                    <View className={`month-balance ${monthBalance >= 0 ? 'positive' : 'negative'}`}>
                      {monthBalance >= 0 ? '+' : ''}{monthBalance.toFixed(2)}
                    </View>
                  </View>
                  <View className="month-details">
                    <View className="detail-item">
                      <View className="detail-label">收入</View>
                      <View className="detail-value income">¥{stat.income.toFixed(2)}</View>
                    </View>
                    <View className="detail-item">
                      <View className="detail-label">支出</View>
                      <View className="detail-value expense">¥{stat.expense.toFixed(2)}</View>
                    </View>
                  </View>
                </View>
              )
            })
          )}
        </ScrollView>
      </View>

      {/* 数据概览 */}
      <View className="data-summary">
        <View className="summary-title">数据概览</View>
        <View className="summary-grid">
          <View className="summary-item">
            <View className="summary-label">记账天数</View>
            <View className="summary-value">{calculateDays()}</View>
          </View>
          <View className="summary-item">
            <View className="summary-label">记录笔数</View>
            <View className="summary-value">{list.length}</View>
          </View>
          <View className="summary-item">
            <View className="summary-label">日均支出</View>
            <View className="summary-value">¥{calculateAvgExpense()}</View>
          </View>
          <View className="summary-item">
            <View className="summary-label">日均收入</View>
            <View className="summary-value">¥{calculateAvgIncome()}</View>
          </View>
        </View>
      </View>
    </View>
  )

  // 计算记账天数
  function calculateDays(): number {
    if (list.length === 0) return 0
    
    const dates = new Set(
      list.map(record => new Date(record.date).toLocaleDateString('zh-CN'))
    )
    return dates.size
  }

  // 计算日均支出
  function calculateAvgExpense(): string {
    const days = calculateDays()
    if (days === 0) return '0.00'
    return (totalExpense / days).toFixed(2)
  }

  // 计算日均收入
  function calculateAvgIncome(): string {
    const days = calculateDays()
    if (days === 0) return '0.00'
    return (totalIncome / days).toFixed(2)
  }
}

export default Discover